<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="别名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入别名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="API地址" prop="serverUrl">
        <el-input
          v-model="queryParams.serverUrl"
          placeholder="请输入API地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="组名" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入组名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['kubernetes:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['kubernetes:user:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['kubernetes:user:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['kubernetes:user:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="别名" align="center" prop="nickName" />
      <el-table-column label="API地址" align="center" prop="serverUrl" />
      <el-table-column label="组名" align="center" prop="groupName" />
      <el-table-column label="有效天数" align="center" prop="expirationDays" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['kubernetes:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['kubernetes:user:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="copyConfig(scope.row)"
            v-hasPermi="['kubernetes:user:download']"
          >获取配置</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改K8s用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" :disabled=readonly />
        </el-form-item>
        <el-form-item label="别名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入别名" />
        </el-form-item>
        <el-form-item label="API地址" prop="serverUrl">
          <el-input v-model="form.serverUrl" placeholder="请输入API地址" />
        </el-form-item>
        <el-form-item label="组名" prop="groupName">
          <el-select v-model="form.groupName" placeholder="请选择" :disabled=readonly>
            <el-option
              v-for="group in groupList"
              :key="group.id"
              :label="group.groupName"
              :value="group.groupName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效天数" prop="expirationDays" >
          <el-popover
            placement="top-start"
            width="200"
            trigger="hover"
            content="该设置仅支持1.21及以上版本">
            <i class="el-icon-question" slot="reference"></i>
          </el-popover>
          <el-input-number v-model="form.expirationDays" placeholder="请输入有效日期" :disabled=readonly :min="1" :max="3650"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, getUserConfig } from '@/api/kubernetes/user'
import { listGroup, getGroup} from "@/api/kubernetes/group";

export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedKubernetesUserRoleBinding: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // K8s用户表格数据
      userList: [],
      // ${subTable.functionName}表格数据
      kubernetesUserRoleBindingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        nickName: null,
        serverUrl: null,
        groupName: null,
      },
      groupQueryParams:{
        pageNum: 1,
        pageSize: 100,
        groupName: null
      },
      // 表单参数
      form: {},
      readonly: true,
      groupList:[],
      // 表单校验
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        serverUrl: [
          { required: true, message: "API地址不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询K8s用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        username: null,
        nickName: null,
        serverUrl: null,
        privateKey: null,
        publicKey: null,
        crtKey: null,
        groupName: null,
        createTime: null,
        expirationDays: 30
      };
      this.kubernetesUserRoleBindingList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.readonly = false;
      listGroup(this.groupQueryParams).then(response => {
        this.groupList = response.rows;
        // this.groupList.push({id:0,groupName:''})
      });
      this.open = true;
      this.title = "添加K8s用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.readonly = true;
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.kubernetesUserRoleBindingList = response.data.kubernetesUserRoleBindingList;
        this.open = true;
        this.title = "修改K8s用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.kubernetesUserRoleBindingList = this.kubernetesUserRoleBindingList;
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除K8s用户编号为"' + ids + '"的数据项？').then(function() {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 下载配置 */
    copyConfig(row){
      const id = row.id;
      getUserConfig(id).then(response=>{
        this.$copyText(response.data).then((e) => {
          this.$message.success('成功复制到粘贴板');
        }, (e) => {
          this.$message.error('获取失败');
        })
      }).catch((err) => {
        this.$message.error(`获取配置数据失败，${err.message}`);
      });
    },
    queryUserRoleBinding(row){},
	/** ${subTable.functionName}序号 */
    rowKubernetesUserRoleBindingIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** ${subTable.functionName}删除按钮操作 */
    handleDeleteKubernetesUserRoleBinding() {
      if (this.checkedKubernetesUserRoleBinding.length == 0) {
        this.$modal.msgError("请先选择要删除的${subTable.functionName}数据");
      } else {
        const kubernetesUserRoleBindingList = this.kubernetesUserRoleBindingList;
        const checkedKubernetesUserRoleBinding = this.checkedKubernetesUserRoleBinding;
        this.kubernetesUserRoleBindingList = kubernetesUserRoleBindingList.filter(function(item) {
          return checkedKubernetesUserRoleBinding.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleKubernetesUserRoleBindingSelectionChange(selection) {
      this.checkedKubernetesUserRoleBinding = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('kubernetes/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
